package com.hengpeng.msls.controller.weixin;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.hengpeng.itfinbase.persist.WechatMerchant;
import com.hengpeng.msls.controller.BaseController;
import com.hengpeng.msls.util.WeixinUtil;

@Controller
public class ClientController extends BaseController {

    public static final Logger log = LogManager.getLogger(ClientController.class);

    /**
     * <pre>
     * 获取微信js 接口 签名信息
     * </pre>
     * 
     * @param request
     * @param response
     * @param map
     * @param url
     * @throws IOException
     */

    @RequestMapping(value = "/getjsapiTikcet")
    @SuppressWarnings("static-access")
    public void getjsapiTikcet(HttpServletRequest request, HttpServletResponse response, ModelMap map,
            String merchantId, String url) throws IOException {
        JSONArray jsonArray = new JSONArray();
        PrintWriter out = response.getWriter();
        WechatMerchant wm = serviceFactory.getActivityService().getWechatMerchantByappId(merchantId);
        if (wm != null && !"".equals(wm)) {
            /**
             * 获取accesstoken
             */
            String accessToken = WeixinUtil.getBaseAccessToken(wm.getAppId(), wm.getAppsecret());

            /**
             * 获取jsapiticket
             */
            String jsapiTicket = WeixinUtil.getBaseJsapiTicket(wm.getAppId(), accessToken);
            /**
             * 生成js 接口 签名信息
             */
            Map<String, String> jsapiValus = WeixinUtil.sign(jsapiTicket, url);
            jsapiValus.put("appId", wm.getAppId());

            /**
             * 返回签名信息
             */
            out.print(jsonArray.fromObject(jsapiValus));
            out.flush();
            out.close();
        }

    }

    /**
     * <pre>
     * 去除特殊符号
     * </pre>
     * 
     * @param str
     * @return
     */
    public static String replaceBlank(String str) {
        String dest = "";
        if (str != null) {
            Pattern p = Pattern.compile("\\s*|\t|\r|\n");
            Matcher m = p.matcher(str);
            dest = m.replaceAll("");
        }
        return dest;
    }

    /**
     * <pre>
     * 获取当前域名
     * </pre>
     * 
     * @param request
     * @return
     */
    private String getPath(HttpServletRequest request) {
        return request.getScheme() + "://" + request.getServerName() + request.getContextPath() + "/";
    }

}